package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false)Map<String,String> searchMap, Model model){
        //调用changgou-service-search微服务
        Map<String,Object> resultMap = skuFeign.search(searchMap);
        model.addAttribute("result",resultMap);
        //搜索条件
        model.addAttribute("searchMap",searchMap);


        //请求地址
        String url = url(searchMap);
        System.out.println("urlurlurlurlurlurl++++********"+url);
        model.addAttribute("url",url);
        return "search";
    }

    private String url(Map<String,String> searchMap) {
        //url地址
        String url ="/search/list";
        if(searchMap!=null && searchMap.size()>0){
            url+="?";
            for (Map.Entry<String,String> entry : searchMap.entrySet()) {
                //如果是排序 则跳过 拼接排序地址 因为有数据
                String key = entry.getKey();
                String value = entry.getValue();
                if(key.equals("sortField") ||
                        key.equals("sortRule")){
                    continue;
                }else {
                    url+=key+"="+entry.getValue()+"&";
                }
            }
            //去掉最后一个&
            if(url.lastIndexOf("&")!=-1){
                url=url.substring(0,url.length()-1);
            }

        }
        return url;
    }

}
